package com.tanhua.server.interceptor;

import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.UserFreeze;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.UserFreezeApi;
import com.tanhua.server.serivce.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private UserFreezeApi userFreezeApi;

    // 处理请求之前，先执行preHandle()方法
    @Override
    public boolean preHandle(
            HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("执行拦截器的preHandle()方法，统一身份认证");

        //1. 从Authorization请求头中获取token信息
        String token = request.getHeader("Authorization");

        //2. 判断，如果请求没有携带token，说明非法用户，认证失败，401
        if (token == null) {
            response.setStatus(401);
            return false;
        }

        //3. 根据token获取用户
        User user = userService.findUserByToken(token);
        if (user == null) {
            response.setStatus(401);
            return false;
        }

        //查询用户的冻结状态     ----xz添加的代码
        UserInfo userInfo = userInfoApi.findById(user.getId());
        //如果处于冻结状态
        if(userInfo != null) { // --> 增加判断是否为空。
            if (userInfo.getUserStatus().equals("2")) {
                //查询冻结范围是否为登录
                UserFreeze userFreeze = userFreezeApi.findByUserId(user.getId());
                if (userFreeze != null) {
                    //如果冻结范围为登录，就不让继续登录
                    if(userFreeze.getFreezingRange() == 1) {
                        response.sendError(401, "登录失败！您的账号已被冻结！冻结原因："+ userFreeze.getReasonsForFreezing());
                        return false;
                    }
                }
            }
        }

        //4. 用户绑定到本地线程对象上
        UserHolder.set(user);

        return true;
    }
}
